package br.com.future.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import br.com.future.dao.interfaces.TipoCobrancaDAOI;
import br.com.future.jdbc.ConnectionFactory;
import br.com.future.log4j.Log4j;
import br.com.future.model.TipoCobranca;

public class TipoCobrancaDAO implements TipoCobrancaDAOI {
	
	//chamando o metodo da classe Log4j.
	static Logger logger = Logger.getLogger(Log4j.class);
	
	private Connection conn = null;
	private boolean flag = true;

	public TipoCobrancaDAO(Connection conn){
		this.conn  = conn;
	}
	public TipoCobrancaDAO(){
		
	}
	
	public List<TipoCobranca> consultar(){
		
		verificarInstanciaDeConnection();
		Statement stmt = null;
		ResultSet rs = null;
		List<TipoCobranca> tiposCobrancas = new ArrayList<TipoCobranca>();
		try {
			String sql = "SELECT CD_COBRANCA, DS_COBRANCA, TX_JUROS, VL_MORA_DIARIA FROM AM_TIPO_COBRANCA";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);			
			
			while(rs.next()){
				TipoCobranca tipoCobranca = new TipoCobranca();
				tipoCobranca.setCodigoCobranca(rs.getInt("CD_COBRANCA"));
				tipoCobranca.setDescricaoCobranca(rs.getString("DS_COBRANCA"));
				tipoCobranca.setTaxaJuros(rs.getDouble("TX_JUROS"));
				tipoCobranca.setValorDiaria(rs.getDouble("VL_MORA_DIARIA"));
				tiposCobrancas.add(tipoCobranca);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			//chamando a mensagem.
			logger.error(e.getMessage());
		}finally{
			if(flag){
				ConnectionFactory.closeConnectionOracle(conn, rs, stmt);
			}
		}
		return tiposCobrancas;
	}
	public TipoCobranca consultarPorId(int id){
		
		verificarInstanciaDeConnection();
		PreparedStatement pstm = null;
		ResultSet rs = null;
		TipoCobranca tipoCobranca = new TipoCobranca();
		try {
			String sql = "SELECT CD_COBRANCA, DS_COBRANCA, TX_JUROS, VL_MORA_DIARIA FROM AM_TIPO_COBRANCA WHERE CD_COBRANCA = ?";
			
			pstm = conn.prepareStatement(sql);
			pstm.setInt(1, id);
			rs = pstm.executeQuery();
			
			while(rs.next()){
				tipoCobranca.setCodigoCobranca(rs.getInt("CD_COBRANCA"));
				tipoCobranca.setDescricaoCobranca(rs.getString("DS_COBRANCA"));
				tipoCobranca.setTaxaJuros(rs.getDouble("TX_JUROS"));
				tipoCobranca.setValorDiaria(rs.getDouble("VL_MORA_DIARIA"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
			//chamando a mensagem.
			logger.error(e.getMessage());
		}finally{
			if(flag){
				ConnectionFactory.closeConnectionOracle(conn, rs, pstm);
			}
		}
		return tipoCobranca;
	}

	private void verificarInstanciaDeConnection() {
		flag = true;
		
		if(conn == null){
			this.conn = ConnectionFactory.getConnection();
		}else{
			flag = false;
		}
	}
}
